package com.lixinlei.springboot_servlet.controller.requestmapping.produces;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.bind.annotation.XmlRootElement;

@RestController
@RequestMapping(path = "/request/mapping/produces")
public class ProducesController {

    /**
     * produces 用于匹配 HTTP 请求中的 Accept 头字段；
     * 同一个 URL 可以通过给 Accept 头字段设置不同的值，获取到不同的数据；
     * 相应的，后端要提供 produces 不同的处理器方法；
     * @return
     */
    @RequestMapping(path = "/myProduces", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public MyData returnJsonValue() {
        return getMyData();
    }

    @RequestMapping(path = "/myProduces", produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public MyData returnXmlValue() {
        return getMyData();
    }

    /**
     * Accept: * / *
     * 如果有多个处理器方法可以处理 Accept: * / * 的请求，SpringMVC 会选第一个匹配到的；
     * @return
     */
    @RequestMapping(path = "/myAcceptAll", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public MyData acceptAllJson() {
        return getMyData();
    }

    /**
     * Accept: * / *
     * @return
     */
    @RequestMapping(path = "/myAcceptAll", produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public MyData acceptAllXml() {
        return getMyData();
    }

    private MyData getMyData() {
        MyData myData = new MyData();
        myData.setFirstName("Xinlei");
        myData.setLastName("Li");
        return myData;
    }

    @XmlRootElement
    private static class MyData {

        private String firstName;
        private String lastName;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

    }

}
